package com.ssm.zy.common.controller;

import com.ssm.zy.common.exception.UnauthenticatedException;
import com.ssm.zy.common.exception.UnauthoriseException;
import com.ssm.zy.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 郑智辰~
 * @version 1.0
 *
 * 所有Controller的父类
 * 作用: 1.设置白名单，效验是否可通行
 *      2.获取JWT令牌claims数据，配置成属性，供所有子类使用
 */
public class BaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Integer userId;
    protected String userName;
    protected Claims claims;//JWT会话管理使用

    @Autowired
    private JWTUtil jwtUtil;

    @ModelAttribute
    public void init(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;

        //设置白名单
        List<String> whiteList = new ArrayList();
        whiteList.add("/user/login.do");
        whiteList.add("/user/register.do");
        whiteList.add("/user/checkUsername.do");
        whiteList.add("/user/checkPhone.do");
        whiteList.add("/user/findCityByParentId.do");
        whiteList.add("/common/fileUpload.do");
        whiteList.add("/post/viewerCheck.do");
        whiteList.add("/post/getLabel.do");
        //判断是否为白名单路径，如果不是则解析JTW，设置属性值
        if (!whiteList.contains(request.getRequestURI())){
            //获取请求头的token信息 (claims)
            Claims claims = this.getClaims(request);

            //获取token令牌信息，设置属性值
            this.claims = claims;
            this.userId = (Integer) claims.get("userId");
            this.userName = (String) claims.get("userName");
        }
    }

    public Claims getClaims(HttpServletRequest request){
        //1.获取token
        String token = request.getHeader("Authorization");
        //2.没有token，说明用户未登录
        if (StringUtils.isEmpty(token)){
            throw new UnauthenticatedException();
        }
        //3.解析token
        Claims claims = jwtUtil.parseJWT(token);
        //4.claims为空，说明用户没有权限
        if (StringUtils.isEmpty(claims)){
            throw new UnauthoriseException();
        }
        return claims;
    }
}
